package com.qlc_demo_api.controller;

import com.alibaba.fastjson.JSONObject;
import com.qlc_demo_api.model.ResponseData;
import com.qlc_demo_api.service.impl.QlcSettingServiceImpl;
import com.qlc_demo_api.util.AESUtils;
import com.qlc_demo_api.util.JWTUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class AuthenController {

    @Autowired
    QlcSettingServiceImpl qlcSettingService;

    /***
     * 执行登录
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/login/regist_login", method = {RequestMethod.POST})
    @ResponseBody
    public ResponseData registLogin(
            @RequestHeader(value = "Terminal-Type", required = false) String terminalType,
            @RequestBody JSONObject jsonObject
    ) throws Exception {
        if (terminalType == null || StringUtils.isEmpty(terminalType)) {
            return ResponseData.fail("不支持的客户端类型!");
        }
        Boolean hasSettingCode = terminalType.equals("WX_OP") && jsonObject.get("settingCode") == null;
        if (jsonObject.get("appId") == null || jsonObject.get("code") == null || hasSettingCode) {
            return ResponseData.fail("必填参数不能为空！");
        }
        String appId = (String) jsonObject.get("appId");
        String code = (String) jsonObject.get("code");
        String settingCode = (String) jsonObject.get("settingCode");
        Boolean settingCodeEmpty = (settingCode == null || settingCode.isEmpty()) && terminalType.equals("WX_OP");
        if (appId.isEmpty() || code.isEmpty() || settingCodeEmpty) {
            return ResponseData.fail("必填参数不能为空！");
        }
        Map<String, Object> userInfo;
        if (terminalType.equals("WX_OP")) {
            userInfo = qlcSettingService.getUserInfo(appId, settingCode, code);
        } else {
            userInfo = qlcSettingService.getUserInfoWXMP(appId, code);
        }
        if (userInfo.get("errMsg") != null) {
            String errMsg = "服务端错误："+ userInfo.get("errMsg");
            return ResponseData.fail(errMsg);
        }
        // 对accessToken进行加密处理
        String accessToken = (String) userInfo.get("accessToken");
        String accessTokenAes = AESUtils.encrypt(accessToken);
        String encryptAccessToken = JWTUtil.createToken(accessTokenAes);
        userInfo.put("accessToken", encryptAccessToken);
        // 对refreshToken进行加密
        String refreshToken = (String) userInfo.get("refreshToken");
        if (!StringUtils.isEmpty(refreshToken)) {
            String refreshTokenAes = AESUtils.encrypt(refreshToken);
            userInfo.put("refreshToken", refreshTokenAes);
        }

        return ResponseData.success().add(userInfo);

    }

    @RequestMapping(value = "/login/refresh_token", method = { RequestMethod.POST })
    @ResponseBody
    public ResponseData refreshToken(@RequestBody JSONObject jsonObject) throws Exception {
        String refreshToken = jsonObject.getString("refreshToken");
        String thirdAppId = jsonObject.getString("thirdAppId");
        if (refreshToken == null || refreshToken.isEmpty() || thirdAppId == null || thirdAppId.isEmpty()) {
            return ResponseData.fail("必填参数不能为空!");
        }
        refreshToken = AESUtils.decrypt(refreshToken);
        Map<String, Object> userInfo = qlcSettingService.refreshTokenFn(thirdAppId, refreshToken);
        if (userInfo.get("errMsg") != null) {
            String errMsg = "服务端错误："+ userInfo.get("errMsg");
            return ResponseData.fail(errMsg);
        }
        // 对accessToken进行加密处理
        String accessToken = (String) userInfo.get("accessToken");
        String accessTokenAes = AESUtils.encrypt(accessToken);
        String encryptAccessToken = JWTUtil.createToken(accessTokenAes);
        userInfo.put("accessToken", encryptAccessToken);
        // 对refreshToken进行加密
        String refreshTokenOrigin = (String) userInfo.get("refreshToken");
        String refreshTokenAes = AESUtils.encrypt(refreshTokenOrigin);
        userInfo.put("refreshToken", refreshTokenAes);
        return ResponseData.success().add(userInfo);
    }

    @RequestMapping(path = "/unauthorized/{message}")
    public ResponseData unauthorized(@PathVariable String message) throws UnsupportedEncodingException {
        return ResponseData.fail(message);
    }

}
